import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import router from '@/router'
import {stringify} from '@/utils'

import fromEntries from 'object.fromentries'

// 挂载
window.axiosOrigin = axios

const service = axios.create({
	// baseURL: '/api/',
	timeout: 10 * 1000
})

service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

service.interceptors.request.use((config) => {
	if (typeof config.data === 'undefined') {
		config.data = {}
	}

	if (['post', 'put'].includes(config.method)) {
		const isFormData = config.data instanceof FormData

		if (! isFormData) {
			config.data = stringify(config.data)
		}
	} else {
		// 去除空值
		config.params = fromEntries(Object.entries(config.params || {}).filter((item) => {
			const value = config.params[item[0]]

			if (value === '') {
				return false
			}

			if (typeof value === 'undefined') {
				return false
			}

			return true
		}))
	}

	return config
}, (error) => {
	console.log(error)
})

service.interceptors.response.use((res) => {
	return {
		success: true,
		data: res.data,
		status: res.status,
		headers: res.headers
	}
}, (error) => {
	console.log(error)

	// 取消请求导致 response 为空
	if (! error.response) {
		! error.__CANCEL__ && Vue.prototype.$toast(error.message || '服务君打盹了，稍等下哈')

		return {
			success: false,
			status: error.response ?. status,
			isCancel: error.__CANCEL__
		}
	}

	let {status, data: {errors, message}} = error.response

	// 登录失效
	if (status === 401) {
		localStorage.removeItem('isLogin')

		! window.isLogin && router.replace(`/login?return_url=${encodeURIComponent(location.href)}`)

		window.isLogin = true

		return {
			success: false
		}
	}

	// noNeedErrorTips 用来控制是否需要弹窗
	! window.noNeedErrorTips && Vue.prototype.$toast(errors || message || '服务不可用，请稍后重试')

	return {
		success: false,
		data: error.response ?. data,
		status: error.response ?. status,
		isCancel: error.__CANCEL__
	}
})

export default service